package com.jeesit.cloud.spot.web.api_controller.gd_contract_record;

import com.jeesit.cloud.annotation.ModuleLog;
import com.jeesit.cloud.dto.LogInfo;
import com.jeesit.cloud.spot.business.impl.IGdContractBiz;
import com.jeesit.cloud.spot.service.IGdContractRecordService;
import com.jeesit.cloud.verify.UserAuthDetail;
import com.jeesit.cloud.constants.LogConstant;
import com.jeesit.cloud.util.ExportExcel;
import com.jeesit.cloud.dto.GdContractRecordDto;
import com.jeesit.cloud.validate.UpdateAction;
import com.jeesit.cloud.validate.CreateAction;
import com.jeesit.cloud.validate.QueryAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.jeesit.cloud.model.*;

import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeesit.cloud.dto.JSONResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 *   相关接口
 *　　
 *   @description GdContractRecord 接口
 *   ---------------------------------
 *   @author lss
 *   @date 2024-02-06
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/v1/gd_contract_record")
@Api(tags = {"高达现货数据"})
public class GdContractRecordController {

    @Autowired
    private IGdContractRecordService gdContractRecordService;
    @Autowired
    private IGdContractBiz gdContractBiz;

    /**
     * @description 获取分页列表
     * ---------------------------------
     * @author lss
     * @date 2024-02-06
     */
    @ApiOperation("获取分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataTypeClass = Integer.class , paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页行数，最少10条，最多100条", dataTypeClass = Integer.class , paramType = "query", required = true)
    })
    @PostMapping(value = "/gd_contract_record_page")
    public JSONResult<Page<GdContractRecord>> getGdContractRecordPage(Authentication authentication,@Validated(QueryAction.class)GdContractRecordDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        Page<GdContractRecord> page=new Page<GdContractRecord>(dto.getPageNo(), dto.getPageSize());
        gdContractRecordService.page(page,dto);
        JSONResult<Page<GdContractRecord>> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setData(page);
        return res;
    }

/**
     * @description 获取列表
     * ---------------------------------
     * @author lss
     * @date 2024-02-06
     */
    @ApiOperation("获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "size", value = "查询数量，最多查询1000条", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping(value = "/gd_contract_record_list")
    public JSONResult<GdContractRecord> getGdContractRecordList(Authentication authentication, @Validated(QueryAction.class)GdContractRecordDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<GdContractRecord> list = gdContractRecordService.list(dto.getSize(),dto);
        JSONResult<GdContractRecord> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setDatas(list);
        return res;
    }


    /**
     * @description 导出列表
     * ---------------------------------
     * @author lss
     * @date 2024-02-06
     */
    @ApiOperation("导出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('GdContractRecord_Export','SUPER_ADMIN')")
    @PostMapping(value = "/gd_contract_record_export")
    public void export(HttpServletResponse response,Authentication authentication, @Validated(QueryAction.class)GdContractRecordDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<GdContractRecord> datas = gdContractRecordService.list(0,dto);
        String[] header = new String[]{"","采购合同编号","销售合同编号","大类","合同量","出库量（签收量）","库存量","合同未出库量","业务机构","业务部门","敞口标记","采销合同","高达业务部门","品名","高达物料关系表","合同敞口","操作时间","",""};
        List<List<Object>> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");
        for(GdContractRecord it : datas){
            List<Object> data = new ArrayList<>();
            data.add(it.getId());
            data.add(it.getPurchaseContractNumber());
            data.add(it.getSaleContractNumber());
            data.add(it.getMatterName());
            data.add(Optional.ofNullable(it.getWeight()).map(s->df.format(s)).orElse(""));
            data.add(Optional.ofNullable(it.getDeliveryWeight()).map(s->df.format(s)).orElse(""));
            data.add(Optional.ofNullable(it.getInventory()).map(s->df.format(s)).orElse(""));
            data.add(Optional.ofNullable(it.getUnDeliveryWeight()).map(s->df.format(s)).orElse(""));
            data.add(it.getGroupName());
            data.add(it.getDepartmentName());
            data.add(it.getExposureFlag());
            data.add(it.getType());
            data.add(it.getGdOrgUuid());
            data.add(it.getDescription());
            data.add(it.getGdRelationUuid());
            data.add(Optional.ofNullable(it.getContractedQuantity()).map(s->df.format(s)).orElse(""));
            data.add(Optional.ofNullable(it.getAddTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getDeleted());
            list.add(data);
        }
        ExportExcel excel = new ExportExcel();
        excel.setName("");
        excel.exportToExcel(response,header,list,0);
    }

    /**
     * @description 新建
     *
     * @author lss
     * @date 2024-02-06
     */
    @ApiOperation("新建")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('GdContractRecord_Add','SUPER_ADMIN')")
    @ModuleLog("GdContractRecord")
    @PostMapping("/gd_contract_record_add")
    public JSONResult<GdContractRecord> saveNewEntity(HttpServletRequest request,Authentication authentication, @Validated(CreateAction.class) GdContractRecordDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<GdContractRecord> res= saveData(user,null,entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "保存，数据ID:"+res.firstData().getId()));
        }
        return res;
    }

    /**
     * @description 更新
     *
     * @author lss
     * @date 2024-02-06
     */
    @ApiOperation("更新 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('GdContractRecord_Modify','SUPER_ADMIN')")
    @ModuleLog("GdContractRecord")
    @PostMapping("/gd_contract_record_edit")
    public JSONResult<GdContractRecord> saveEditEntity(HttpServletRequest request,Authentication authentication,@Validated(UpdateAction.class) GdContractRecordDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<GdContractRecord> res= saveData(user,entity.getId(),entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "更新，数据ID:"+res.firstData().getId()));
        }
        return res;
    }

    private JSONResult<GdContractRecord> saveData(User user,Long id,GdContractRecordDto entity){
        JSONResult<GdContractRecord> res = new JSONResult<>();
        GdContractRecord it = new GdContractRecord();
        if(id==null){
            it.setDeleted(false);
        } else {
            it = gdContractRecordService.getById(entity.getId());
        }
        it.setPurchaseContractNumber(entity.getPurchaseContractNumber());
        it.setSaleContractNumber(entity.getSaleContractNumber());
        it.setMatterName(entity.getMatterName());
        it.setWeight(entity.getWeight());
        it.setDeliveryWeight(entity.getDeliveryWeight());
        it.setInventory(entity.getInventory());
        it.setUnDeliveryWeight(entity.getUnDeliveryWeight());
        it.setGroupName(entity.getGroupName());
        it.setDepartmentName(entity.getDepartmentName());
        it.setExposureFlag(entity.getExposureFlag());
        it.setType(entity.getType());
        it.setGdOrgUuid(entity.getGdOrgUuid());
        it.setDescription(entity.getDescription());
        it.setGdRelationUuid(entity.getGdRelationUuid());
        it.setContractedQuantity(entity.getContractdQuantity());
        gdContractRecordService.saveOrUpdate(it);
        res.setData(it);
        res.setSuccess(true);
        res.setMessage("保存成功");
        return res;
    }


    /**
     * @description 删除
     *
     * @author lss
     * @date 2024-02-06
     */
    @ApiOperation("删除")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
        @ApiImplicitParam(name = "ids", value = "删除id（支持批量删除）", dataTypeClass = Long.class , allowMultiple = true,paramType = "query", required = true),
    })
    @PreAuthorize("hasAnyAuthority('GdContractRecord_Remove','SUPER_ADMIN')")
    @ModuleLog("GdContractRecord")
    @PostMapping("gd_contract_record_del")
        public JSONResult<Void> delEntity(HttpServletRequest request,Authentication authentication,@Size(min=1,max=50,message = "请选择要删除数据") Long[] ids) throws Exception{
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<Void> res = new JSONResult<>();
        for(int i=0;i<ids.length;i++){
            GdContractRecord it = gdContractRecordService.getById(ids[i]);
            gdContractRecordService.removeById(it.getId());
        }
        request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "删除，数据ID:" + StringUtils.join(ids)));
        res.setMessage("删除成功");
        res.setSuccess(true);
        return res;
    }

    @ApiOperation("手动同步")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
    })

    @ModuleLog("GdContractRecord")
    @PostMapping("gd_contract_record_port")
    public JSONResult<Void> portGd(HttpServletRequest request,Authentication authentication) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<Void> res = new JSONResult<>();
        gdContractBiz.portGd();
        request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "手动同步高达数据"));
        res.setMessage("同步成功");
        res.setSuccess(true);
        return res;
    }

}

